package com.gnerv.business.platform.common.dhtmlx;


import java.util.ArrayList;
import java.util.List;

public class BuildDhtmlxTree {

	public static <T> DhtmlxTree build(List<DhtmlxTree> nodes) {

		if (nodes == null) {
			return null;
		}
		List<DhtmlxTree> topNodes = new ArrayList<DhtmlxTree>();

		for (DhtmlxTree children : nodes) {

			String pid = children.getpId();
			if (pid == null || "0".equals(pid)) {
				topNodes.add(children);

				continue;
			}

			for (DhtmlxTree parent : nodes) {
				String id = parent.getId();
				if (id != null && id.equals(pid)) {
					parent.getItem().add(children);
					continue;
				}
			}

		}

		DhtmlxTree root = new DhtmlxTree();
		if (topNodes.size() == 1) {
            root = topNodes.get(0);
		} else {
			root.setId("0");
			root.setpId("");
			root.setItem(topNodes);
			root.setText("顶级节点");
			root.setOpen(true);
		}

		DhtmlxTree baseTree = new DhtmlxTree();
		baseTree.setId("0");
		baseTree.getItem().add(root);
		baseTree.setOpen(true);

		return baseTree;
	}

	public static DhtmlxTree buildList(List<DhtmlxTree> nodes, String idParam) {
		if (nodes == null) {
			return null;
		}
		List<DhtmlxTree> topNodes = new ArrayList<DhtmlxTree>();

		for (DhtmlxTree children : nodes) {

			String pid = children.getpId();
			if (pid == null || idParam.equals(pid)) {
				topNodes.add(children);
				continue;
			}
			for (DhtmlxTree parent : nodes) {
				String id = parent.getId();
				if (id != null && id.equals(pid)) {
					parent.getItem().add(children);
					continue;
				}
			}

		}

        DhtmlxTree baseTree = new DhtmlxTree();
        baseTree.setId("0");
        baseTree.setItem(topNodes);
        baseTree.setOpen(true);

		return baseTree;
	}

}